<template>
  <div>
    <el-cascader
      v-if="addrType == 'cascader'"
      filterable
      :props="{
        value: 'id',
        label: 'name',
        multiple: multiple,
        checkStrictly: checkStrictly,
        expandTrigger: expandTrigger,
      }"
      clearable
      v-model="selectedValue"
      collapse-tags
      :options="cascaderOptions"
      placeholder="请填写"
      :popper-class="getPopperClass()"
      @change="handlerChange"
    ></el-cascader>

    <el-popover v-else placement="bottom-start" width="500" trigger="click">
      <el-input
        clearable
        v-model="addrText"
        slot="reference"
        placeholder="点击选择地址"
        :readonly="false"
      >
      </el-input>
      <el-tabs v-model="activeName" @tab-click="">
        <el-tab-pane label="省" name="deep_0">
          <AddrList
            :addr="tabsList.deep_0_list"
            @change="handlerAddrChange"
            name="deep_0"
          />
        </el-tab-pane>
        <el-tab-pane label="市" name="deep_1">
          <AddrList
            :addr="tabsList.deep_1_list"
            @change="handlerAddrChange"
            name="deep_1"
          />
        </el-tab-pane>
        <el-tab-pane label="区" name="deep_2">
          <AddrList
            :addr="tabsList.deep_2_list"
            @change="handlerAddrChange"
            name="deep_2"
          />
        </el-tab-pane>
        <el-tab-pane label="街道" name="deep_3">
          <AddrList
            :addr="tabsList.deep_3_list"
            @change="handlerAddrChange"
            name="deep_3"
          />
        </el-tab-pane>
      </el-tabs>
    </el-popover>
  </div>
</template>

<script>
import { GetAreaCityTree } from "@/api/system/addressbase";
import AddrList from "./addrList.vue";
import { pinyin } from "pinyin-pro";
export default {
  components: { AddrList },
  props: {
    isLeaf: {
      type: Number,
      default: 4,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    checkStrictly: {
      type: Boolean,
      default: false,
    },
    disableFirstAndSecondLevel: {
      type: Boolean,
      default: false,
    },
    expandTrigger: {
      type: String,
      default: "click",
    },
    addrType: {
      type: String,
      default: "cascader",
    },
  },
  data() {
    return {
      addrText: "",
      activeName: "deep_0",
      selectedValue: null,
      cascaderOptions: [], // 存储搜索结果
      tabsCheck: [],
      tabsList: {
        deep_0_list: {},
        deep_1_list: {},
        deep_2_list: {},
        deep_3_list: {
          // obj: {},
        },
      },
    };
  },
  methods: {
    handlerAddrChange(nodes, currentName) {
      console.log(nodes, currentName);
      const currIndex = Number(currentName.split("_")[1]) + 1;
      let result;
      if (this.isLeaf > currIndex) {
        this.activeName = "deep_" + currIndex;
        result = this.classifyProvinces(nodes.children);
      }
      switch (currentName) {
        case "deep_0":
          this.tabsList.deep_1_list = result;
          this.activeName = "deep_1";
          this.tabsCheck[0] = { id: nodes.id, name: nodes.name };
          this.tabsCheck.splice(1);
          break;
        case "deep_1":
          this.tabsList.deep_2_list = result;
          this.activeName = "deep_2";
          this.tabsCheck[1] = { id: nodes.id, name: nodes.name };
          this.tabsCheck.splice(2);
          break;
        case "deep_2":
          this.tabsList.deep_3_list = result;
          this.activeName = "deep_3";
          this.tabsCheck[2] = { id: nodes.id, name: nodes.name };
          this.tabsCheck.splice(3);
          break;
        case "deep_3":
          this.tabsCheck[3] = { id: nodes.id, name: nodes.name };
          document.body.click();
          break;
      }
      console.log(this.tabsCheck.map((i) => i.name).join("/"), "12313123132");
      this.addrText = this.tabsCheck.map((i) => i.name).join("/");
    },
    handlerChange(node) {
      console.log(node);
      this.$emit("change", node);
    },
    show(selNodes) {
      this.selectedValue = selNodes;
    },
    getPopperClass() {
      return `label-check ${
        this.disableFirstAndSecondLevel ? "disableFirstAndSecondLevel" : ""
      }`.trim();
    },
    getNodesUpToLevel(nodes, n) {
      if (n < 0) {
        throw new Error("Level must be non-negative.");
      }
      // 如果 nodes 不是数组，直接返回空数组
      if (!Array.isArray(nodes)) {
        return [];
      }
      // 定义递归函数
      const dfs = (currentNodes, currentLevel) => {
        if (currentLevel > n) return []; // 超过指定层级，返回空数组
        // 创建一个新的数组来保存当前层级的结果
        const result = [];
        currentNodes.forEach((node) => {
          // 创建新的节点对象
          const newNode = {
            id: node.id,
            name: node.name,
            children: [],
          };
          // 如果当前层级小于 n，才继续处理子节点
          if (currentLevel < n && node.children) {
            newNode.children = dfs(node.children, currentLevel + 1); // 递归处理子节点
          } else {
            delete newNode.children;
          }
          // 将当前节点添加到结果中
          result.push(newNode);
        });
        return result; // 返回当前层级的节点
      };
      return dfs(nodes, 1);
    },
    // 获取汉字的首字母
    getFirstLetter(data) {
      if (!data || !data.name) {
        return "";
      }
      const firstChar = data.name.charAt(0);
      const pinyinResult = pinyin(firstChar, {
        toneType: "none", // 不需要音调
        type: "first", // 只获取首字母
      });
      return pinyinResult[0].toUpperCase(); // 将首字母转换为大写
    },
    // 分类函数
    classifyProvinces(provinces) {
      return provinces.reduce((acc, province) => {
        const firstLetter = this.getFirstLetter(province).toUpperCase(); // 获取首字母并转为大写
        // if (!acc[firstLetter]) {
        //   acc[firstLetter] = []; // 如果首字母不存在，初始化一个数组
        // }
        // acc[firstLetter].push(province); // 将省份添加到对应的首字母数组中
        // return acc;
        let groupKey = '';
        if (firstLetter >= 'A' && firstLetter <= 'G') {
          groupKey = 'A~G';
        } else if (firstLetter >= 'H' && firstLetter <= 'N') {
          groupKey = 'H~N';
        } else if (firstLetter >= 'O' && firstLetter <= 'T') {
          groupKey = 'O~T';
        } else if (firstLetter >= 'U' && firstLetter <= 'Z') {
          groupKey = 'U~Z';
        } else {
          groupKey = "Other"; // 处理不在 A-Z 范围内的情况
        }
        if (!acc[groupKey]) {
          acc[groupKey] = []; // 如果分组不存在，初始化一个数组
        }
        acc[groupKey].push(province); // 将省份添加到对应的分组中
        return acc;
      }, { 'A~G': [], 'H~N': [], 'O~T': [], 'U~Z': [], });
    },
    async init_cascader() {
      let result = { data: undefined };
      if (!this.$store.state.addr.addrData) {
        // 没有缓存数据
        result = await GetAreaCityTree();
        this.$store.commit("addr/SET_ADDR", result.data);
      } else {
        // 存在缓存数据
        result.data = this.$store.state.addr.addrData;
      }
      const cascOp = this.getNodesUpToLevel(result.data, this.isLeaf);

      this.cascaderOptions = cascOp;
    },
    async init_tabs() {
      let result = { data: undefined };
      if (!this.$store.state.addr.addrData) {
        // 没有缓存数据
        result = await GetAreaCityTree();
        this.$store.commit("addr/SET_ADDR", result.data);
      } else {
        // 存在缓存数据
        result.data = this.$store.state.addr.addrData;
      }
      const cascOp = this.getNodesUpToLevel(result.data, this.isLeaf);
      this.cascaderOptions = cascOp;
      // 使用分类函数
      const classifiedProvinces = this.classifyProvinces(cascOp);
      this.tabsList.deep_0_list = classifiedProvinces;
      console.log(classifiedProvinces);
    },
  },
  created() {
    if (this.addrType == "cascader") {
      this.init_cascader();
    } else {
      this.init_tabs();
    }
  },
};
</script>

<style lang="scss">
.label-check {
  .el-cascader-node .el-radio {
    width: 100%;
    height: 100%;
    z-index: 10;
    position: absolute;
    top: 10px;
    right: 10px;
  }

  .el-cascader-node .el-radio__input {
    visibility: hidden;
  }

  /* 这个样式针对IE有用，不考虑IE的可以不用管*/
  .el-cascader-node .el-cascader-node__postfix {
    top: 10px;
  }
}

.disableFirstAndSecondLevel {
  .el-cascader-panel {
    .el-scrollbar:first-child {
      .el-checkbox {
        display: none !important;
      }
    }

    .el-scrollbar:nth-child(2) {
      .el-checkbox {
        display: none !important;
      }
    }
  }
}
</style>
